<template>
    <div class="page">
        <h2>数组扁平化</h2>
        <p>递归实现</p>
        <pre style="font-size:10px">
let arr = [1, [2, [3, 4, 5]]];
function flatten(arr: any[]): any[] {
    let result: any[] = [];
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] instanceof Array) {
            result = result.concat(flatten(arr[i]))
        } else {
            result.push(arr[i])
        }
    }
    return result;
}
console.log(flatten(arr))
        </pre>
        <p>reduce 函数迭代</p>
        <p>扩展运算符实现</p>
        <p>split 和 toString</p>
        <p>ES6 中的 flat：arr.flat(Infinity);</p>
    </div>
</template>

<script setup lang="ts">
import {onMounted} from 'vue'

let arr = [1, [2, [3, 4, 5]]];

//递归
function flatten(arr: any[]): any[] {
    let result: any[] = [];
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] instanceof Array) {
            result = result.concat(flatten(arr[i]))
        } else {
            result.push(arr[i])
        }
    }
    return result;
}
console.log(flatten(arr))
//reduce + 递归
function reduce(arr: any[]): any[] {
    return arr.reduce(function (prev, next) {
        if(Array.isArray(next)){
            return [...prev,...reduce(next)]
        }
        return [...prev,next]
    }, [])
}
console.log(reduce(arr))
// some + 扩展 ...
function some(arr: any[]): any[] {
    while (arr.some((item)=>Array.isArray( item))){
        arr = [].concat(...arr)
    }
    return arr;
}


onMounted(() => {

});

</script>

<style scoped lang="less">

</style>